package com.platform.user.websocket;

import com.alibaba.fastjson.JSON;
//import com.group7.mall.dao.TbMessageDao;
//import com.group7.mall.entity.TbMessage;
import com.platform.user.dao.ChatMessageDao;
import com.platform.user.entity.ChatMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//对外公布的一个后端站点
//ws://localhost:8080/websocket/用户id
@ServerEndpoint(value = "/websocket/{userId}/{roomId}")
@Component
public class WebSocketEndPoint {
    //与某个客户端的连接会话，需要他来给客户端发送数据
    private Session session;

//    @Resource
//    private ChatMessageDao chatMessageDao;

    @Autowired
    public void setChatMessageDao(ChatMessageDao chatMessageDao) {
        WebSocketEndPoint.chatMessageDao = chatMessageDao;
    }

    private static ChatMessageDao chatMessageDao;

    // 连接建立成功调用的方法
    @OnOpen
    public synchronized void onOpen(Session session, @PathParam("userId") String userId, @PathParam("roomId") String roomId) {
        // 把会话加入连接池中
        // userId通过用户传入，session是系统自动产生
        System.out.println("连接打开，用户id：" + userId);
        System.out.println("连接打开，聊天室id：" + roomId);
        System.out.println("连接打开，sessionId：" + session.getId());
        System.out.println();

        // 存储用户的所有session
        List<Session> userSessionList = SessionPool.userToSessionListMap.get(userId);
        if (userSessionList == null) {
            userSessionList = new ArrayList<>();
        }
        userSessionList.add(session);
        SessionPool.userToSessionListMap.put(userId, userSessionList);

        // 存储聊天室内的所有session
        List<Session> roomSessionList = SessionPool.roomToSessionListMap.get(roomId);
        if (roomSessionList == null) {
            roomSessionList = new ArrayList<>();
        }
        roomSessionList.add(session);
        SessionPool.roomToSessionListMap.put(roomId, roomSessionList);

        // SessionPool.sessions.put(userId, session);
    }

    //关闭会话的时候
    @OnClose
    public synchronized void onClose(Session session, @PathParam("userId") String userId, @PathParam("roomId") String roomId) throws IOException {
        System.out.println("连接关闭，用户id：" + userId);
        System.out.println("连接关闭，聊天室id：" + roomId);
        System.out.println("连接关闭，sessionId：" + session.getId());
        System.out.println();

        // 清除用户指定的session
        List<Session> userSessionList = SessionPool.userToSessionListMap.get(userId);
        if (userSessionList != null) {
            userSessionList.remove(session);
        }
        SessionPool.userToSessionListMap.put(userId, userSessionList);


        // 清除聊天室内指定的session
        List<Session> roomSessionList = SessionPool.roomToSessionListMap.get(roomId);
        if (roomSessionList != null) {
            roomSessionList.remove(session);
        }
        SessionPool.roomToSessionListMap.put(roomId, roomSessionList);

//        SessionPool.close(session.getId());
        session.close();
    }

    //接收客户端的消息后调用的方法，在这里可以进行各种业务逻辑的操作
    @OnMessage
    public synchronized void onMessage(String messageObj, Session session) throws IOException {
        Map<String, Object> params = JSON.parseObject(messageObj, HashMap.class);
        String userId = params.get("userId").toString();
        String roomId = params.get("roomId").toString();
        String message = params.get("message").toString();
        String messageType = params.get("messageType").toString();
        String timeStamp = params.get("timeStamp").toString();
        String id = params.get("id").toString();

        // 对聊天室内的所有session群发
        System.out.println("roomId: " + roomId);
        List<Session> sessionList = SessionPool.roomToSessionListMap.get(roomId);
        if (sessionList != null) {
            for (Session x : sessionList) {
                Object lock = SessionPool.sessionLocks.computeIfAbsent(x.getId(), k -> new Object());
                synchronized (lock) { // 加锁
                    try {
                        x.getAsyncRemote().sendText(messageObj); // 发送消息
                        System.out.println("Message sent to session: " + x.getId());
                    } catch (IllegalStateException e) {
                        System.err.println("Failed to send message to session: " + x.getId());
                        e.printStackTrace();
                    }
                }
            }
        } else {
            System.out.println("roomSessionList为空");
        }

        if ("-1".equals(id)) {
            System.out.println("在onClose中将用户移出聊天室");
        } else {
            // 存储数据库中
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setMessage(message);
            chatMessage.setUserId(Integer.parseInt(userId));
            chatMessage.setRoomId(Integer.parseInt(roomId));
            chatMessage.setMessageType(Integer.parseInt(messageType));
            chatMessage.setTimeStamp(timeStamp);
            System.out.println(chatMessage.toString());
            chatMessageDao.insert(chatMessage);
        }
    }
}